package com.huatai.bpmn.commom.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.stream.Collectors;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpsUtils {

    public static String sendGet(String url, Map<String, String> headers, Map<String, String> body) throws Exception {
        String paramsStr = "";
        if(body!= null){
            paramsStr = body.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        }
        if (!paramsStr.isEmpty()) {
            url += "?" + paramsStr;
        }

        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        HostnameVerifier ignoreHostnameVerifier = new MyHostnameVerifier();
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, new TrustManager[]{new MyX509TrustManager1()}, new SecureRandom());
        con.setSSLSocketFactory(sslContext.getSocketFactory());
        con.setHostnameVerifier(ignoreHostnameVerifier);

        if(headers!= null){
            headers.forEach(con::setRequestProperty);
        }

        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    public static String sendPost(String url, Map<String, String> headers, Map<String, String> data) throws Exception {
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        HostnameVerifier ignoreHostnameVerifier = new MyHostnameVerifier();
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, new TrustManager[]{new MyX509TrustManager1()}, new SecureRandom());
        con.setSSLSocketFactory(sslContext.getSocketFactory());
        con.setHostnameVerifier(ignoreHostnameVerifier);
        if(headers!= null){
            headers.forEach(con::setRequestProperty);
        }
        String paramsStr = "";
        if(data!= null){
            paramsStr = data.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        }


        con.setDoOutput(true);
        con.getOutputStream().write(paramsStr.getBytes());


        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }



}
/**
 * 实现X509TrustManager接口，信任所有
 */
class MyX509TrustManager1 implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

/**
 * 实现HostnameVerifier接口，忽略HTTPS主机验证
 */
class MyHostnameVerifier implements HostnameVerifier {

    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}


